
$(function () {
    function getUrlParam(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return decodeURI(r[2]); return null;
    }
    //地址
    var address='http://tomcat01.cqmjk.com:8080';
    var shopDescription;
    //默认选择型号
    var  modelName;
    //商品名称
    var  shopName;
    //商品价格
    var shopPrice;
    //默认选中颜色
    var colorName;
    //用户信息请求
    var contactPhone;
    //是否收藏
    var collectionStatus;
    //获取的商品id
    var shopID="99";
    //var shopID=getUrlParam('commodityId');
    //token
    var token="589e71600e83df40d38eb7587ab9157e";
    //var token=getUrlParam('token');
    //version
    var version="1.0";
    //phoneModel
    var phoneModel="test";
    //systemVersion
    var systemVersion="test";
    //phoneType
    var phoneType="test";
    //选择后的商品id
    var selectShopId;
    //userID
    var userID=122;
    //商品type
    var shopType=4;
    /*var shopDescription;
     //默认选择型号
     var  modelName;
     //默认选中颜色
     var colorName;
     //用户信息请求
     var contactPhone;
     //是否收藏
     var collectionStatus;
     //获取的商品id
     var shopID=getUrlParam('commodityId');
     //选择后的商品id
     var selectShopId;
     //userID
     var userID=getUrlParam('userId');
     //商品type
     var shopType=getUrlParam('type');
     //商品库存;
     var stock;
     //token
     var token=getUrlParam('token');
     //version
     var version=getUrlParam('version');
     //phoneModel
     var phoneModel=getUrlParam('phoneModel');
     //systemVersion
     var systemVersion=getUrlParam('systemVersion');
     //phoneType
     var phoneType=getUrlParam('phoneType');*/

    //商品图片
    var coverUrlImg;
    //库存
    var stock;
    function getCount(i){
        return parseInt(i)
    }
    //获取url
    $.ajax({
        url:address+'/api/1/findbycommodityid',
        data:{
            commodityId:shopID,
            userId:userID,
            token:token,
            version:version,
            phoneModel:phoneModel,
            systemVersion:systemVersion,
            phoneType:phoneType,
            type:shopType
        },
        async:false,
        dataType:'json',
        success:function (result) {
            //console.log(result);
         
            //库存
            collectionStatus=result.value.collectionStatus;
			   //alert(collectionStatus);
            var shop=result.value.shopCommodity;
            stock=shop.totalNum;
            var shopDes=result.value.shopDescription;
            contactPhone=result.value.contactPhone;
            shopID=shop.id;
            modelName=shop.modelName;
            colorName=shop.colorName;
            coverUrlImg=address+shop.coverUrl;
            $('.shopCarHeader>div:eq(0) img').attr('src',address+shop.coverUrl);
            shopName=shop.name;
            shopPrice='￥'+shop.price
            $('.shop_info').attr('number',shop.number);
            $('.goods_show img').attr('src',address+shop.coverUrl);
            $('.shop_name').text(shop.name);
            $('.shop_price').text('￥'+shop.price);
            //商品说明
             var shop_explain;
            var lens=shop.lableName.length;
            if(shop.lableName.substring(lens-1)==','){
                var newstrs=shop.lableName.substring(0,shop.lableName.length-1);
                shop_explain=newstrs.split(',');
            }
             var shop_explainlis='';
            for(var i=0;i<shop_explain.length;i++){
                if(i>4){
                   break
                }else{
                    shop_explainlis+='<li>'+shop_explain[i]+'</li>';
                }

            }
            //商品说明弹框
            var shopDesLis='';
            for(var z in shopDes){
                shopDesLis+='<li>'+shopDes[z]['description']+'</li>'
                $('.shopExplainMiddle ul').html(shopDesLis)
            }

            $('.shop_info ul').html(shop_explainlis);
            //型号颜色
            $('.shop_model ul').html('<li >已选择<span class="shopNum">1</span>件</li><li class="shopModel">'+shop.modelName+'</li><li class="shopColor">'+shop.colorName+'</li>')
            //图文详情
            var len=shop.commodityDetailImgUrl.length;
            if(shop.commodityDetailImgUrl.substring(len-1)==','){
                var newstr=shop.commodityDetailImgUrl.substring(0,shop.commodityDetailImgUrl.length-1);
                for(var j=0;j< newstr.split(',').length;j++){
                    imgSrc=address+newstr.split(',')[j];
                    $('.image-textContainer').append('<a href="'+imgSrc+'" class="example-image-link" data-lightbox="example-set"><img src="'+imgSrc+'" ></a>')
                }
            }else{
                for(var j=0;j< shop.commodityDetailImgUrl.split(',').length;j++){
                    imgSrc=address+shop.commodityDetailImgUrl.split(',')[j];
                    $('.image-textContainer').append('<a href="'+imgSrc+'" class="example-image-link" data-lightbox="example-set"><img src="'+imgSrc+'" ></a>')
                }
            }


            //产品参数
            var parameterTable=$('.parameter table tbody');

            parameterTable.append('<tr><td>参数名称</td><td>参数值</td></tr>')
            //console.log(shop.commodity);
           var commodity= shop.commodity;
            var base = new Base64();
           var jsonDecode=JSON.parse( base.decode(commodity));
            for(var key in jsonDecode){
                parameterTable.append('<tr><td>'+key+'</td><td>'+jsonDecode[key]+'</td></tr>')
            }




            //for(var n in shop){
            //    if(n=='parametersProductName'){
            //        if(!shop[n]==''){
            //            parameterTable.append('<tr><td>商品名称</td><td>'+shop[n]+'</td></tr>')
            //        }
            //    }else if(n=='parametersBrand'){
            //        if(!shop[n]==''){
            //            parameterTable.append('<tr><td>品牌</td><td>'+shop[n]+'</td></tr>')
            //        }
            //    }
            //}
            //包装售后
            /*------------包装清单------------*/
            var arr=shop.packingList.split('，');
            var packingListlis='';
            for(var m=0;m<arr.length;m++){
                packingListlis+='<li>'+arr[m]+'</li>';
            }
            $('.packingList').html(packingListlis)
            /*------------售后服务------------*/
            $('.afterSalesService ul').html('<li>'+shop.afterSalesService+'</li>')

        },error:function () {
            console.log('加载失败')
        }
    })
    //正品保证
    $('.shop_info>div>div').on('click',function(){
        $('.shopExplain').slideDown(500);
        $('.wrapper').show();
        $('.wrapper').css({
            height:$(document).height()+'px'
        })
        $('html').css({
            'overflow':'hidden'
        })
        $(document.body).css({
            'overflow':'hidden'
        })
        $('.close').click(function () {
            $('.shopExplain').slideUp(500);
            $('.wrapper').hide();
            $('html').css({
                'overflow':'visible'
            })
            $(document.body).css({
                'overflow':'visible'
            })
        })
    })
    //选择型号
    $('.shop_model').on('click',function(){
        var shopNum=$('.shopNum').text();
        $(document.body).append('<div class="shopCar" ><div class="shopCarHeader"><div><img src="" alt="商品缩略图" class="detailsImg"></div><div style="margin-left: .5rem" ><p style="font-size: .7rem;margin-top: 1rem">'+shopName+'</p><p style="font-size: .7rem;color:#D20F0F;margin-top: .85rem">'+shopPrice+'</p></div><div><p style="font-size:1.2rem;color: black;margin-top: 1rem;margin-top: 1rem" class="close"> &#xd7;</p></div></div><div class="shopCarMiddle model"><p style="font-size: .7rem;margin-top: .5rem">型号</p><div class="shop_color"></div></div><div class="shopCarMiddle color"><p style="font-size: .7rem;margin-top: .5rem">颜色</p><div class="shop_color"></div></div><div class="shopCarFooter"><p>数量</p><div><div class="reduce">-</div><div class="count">'+shopNum+'</div><div class="add">+</div></div></div><div class="jionShopCar"><a href="javascript:;" id="addShopCar">确定</a></div></div>')
        $('.shopCar').slideDown(500);
        $('.wrapper').show();
        $('.wrapper').css({
            height:$(document).height()+'px'
        });
        $('html').css({
            'overflow':'hidden'
        })
        $(document.body).css({
            'overflow':'hidden'
        })
        //购物车请求
        $.ajax({
            url:address+'/api/1/findbynumber',
            data:{
                number:$('.shop_info').attr('number'),
                commodityId:shopID,
                userId:userID,
                token:token,
                version:version,
                phoneModel:phoneModel,
                systemVersion:systemVersion,
                phoneType:phoneType,
                type:shopType
            },
            dataType:'json',
            success:function (result) {
                console.log(result)
                var models='';
                var colors='';
                var num=0;
                var modelArr=result.value.commodityInfo;
                $('.detailsImg').attr('src',coverUrlImg)
                //型号
                for(var x in modelArr){
                    for(var y in modelArr[x]){
                        models+='<p>'+y+'</p>'
                    }
                }
                $('.model .shop_color').html(models);
                $('.model .shop_color p').each(function () {
                    if($(this).text()==modelName){
                        $(this).addClass('shoCar_active')
                    }
                    $(this).on('click',function(){
                        $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                        $('.color .shop_color').html('');
                        //对应型号的颜色
                        if($(this).hasClass('shoCar_active')){
                            var color=$(this).text();
                            colors='';
                            for(var x in modelArr[0][color][0]){
                                var id=modelArr[0][color][0][x]['id'];
                                colors+='<p id="'+id+'">'+x+'</p>'
                            }
                            $('.shopCarMiddle .color .shop_color').html(1)
                        }
                    });

                })
                //颜色
                for(var z in modelArr[0][modelName][0]){
                    colors+='<p>'+z+'</p>'
                }
                $('.color .shop_color').html(colors);
                $('.color .shop_color p').each(function () {
                    if($(this).text()==colorName){
                        $(this).addClass('shoCar_active')
                    }
                    $(this).on('click',function(){
                        $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                    })

                })
                $('.model .shop_color p').each(function () {
                    if($(this).text()==modelName){
                        $(this).addClass('shoCar_active')
                    }
                    $(this).on('click',function(){
                        $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                        $('.color .shop_color').html('');
                        //对应型号的颜色
                        if($(this).hasClass('shoCar_active')){
                            var color=$(this).text();
                            colors='';
                            for(var x in modelArr[0][color][0]){
                                colors+='<p id="'+modelArr[0][color][0][x]['id']+'">'+x+'</p>'
                            }
                            $('.color .shop_color').html(colors)
                            $('.color .shop_color p').each(function () {
                                if($(this).text()==colorName){
                                    $(this).addClass('shoCar_active')
                                }
                                $(this).on('click',function(){
                                    $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');

                                })

                            })
                        }
                    });

                })
            },error:function () {
                console.log('加载失败')
            }
        })
        var num=parseInt(shopNum);
        //商品数量
        //减少商品数
        $('.reduce').on('click',function () {
            if(num==1){
                num=1
            }else {
                num--;
            }
            $('.count').html(num);
        })
        //增加商品数
        $('.add').on('click',function () {
            num++;
            $('.count').html(num);
        })
        //关闭购物车弹框
        $('.close').click(function () {
            $('.shopCar').slideUp(500);
            $('.wrapper').hide();
            $('html').css({
                'overflow':'visible'
            })
            $(document.body).css({
                'overflow':'visible'
            })
           setTimeout(function(){
               $('.shopCar').remove();
           },500)
        })
        //确定
        $('#addShopCar').click(function () {
            $('.shopCar').slideUp(500);
            $('.wrapper').hide();
            $('html').css({
                'overflow':'visible'
            })
            $(document.body).css({
                'overflow':'visible'
            })
            setTimeout(function(){
                $('.shopCar').remove();
            },500)
            $('.shopNum').text($('.count').text());
            $('.shopModel').text($('.shoCar_active').eq(0).text())
            $('.shopColor').text($('.shoCar_active').eq(1).text());
           var s=parseInt($('.count').text());
            if(s>stock){
                $(document.body).append('<div class="cancelCollect"><p>库存不足，掌柜的正在备货，请稍等~ </p></div>');
                $('.cancelCollect').css({
                    left:($(document).innerWidth()-$('.cancelCollect').innerWidth())/2+'px'
                });
                setTimeout(function () {
                    $('.cancelCollect').remove()
                },1000)
            }
        })
    })
    //立即购买
    $('.buyNow').on('click',function(){
        if(stock<=0){
            $(document.body).append('<div class="cancelCollect"><p>库存不足，掌柜的正在备货，请稍等~ </p></div>');
            $('.cancelCollect').css({
                left:($(document).innerWidth()-$('.cancelCollect').innerWidth())/2+'px',
            });
            setTimeout(function () {
                $('.cancelCollect').remove()
            },1000)
        }else{
            if(selectShopId==undefined){
                selectShopId=shopID
            }
            var test1={
                subjectImpl:function(){
                    SubjectJavaScriptImpl.goBuyToNow(getCount($('.shopNum').text())+','+selectShopId);
                }
            };
            test1.subjectImpl();
        }


    })
    //加入购物车
    $('.addShopcar').on('click',function () {
        //token判断
        if(token=='f47ae89213514fa79dad5107662e9c24'){
            var test2={
                subjectImp1:function(){
                    SubjectJavaScriptImpl.loginOUT('never_have_bug');
                }
            };
            test2.subjectImp1();
        }else{
            var shopNum=$('.shopNum').text();
            var num=parseInt(shopNum);
            $(document.body).append('<div class="shopCar" ><div class="shopCarHeader"><div><img src="" alt="商品缩略图" class="detailsImg"></div><div style="margin-left: .5rem" ><p style="font-size: .7rem;margin-top: 1rem">'+shopName+'</p><p style="font-size: .7rem;color:#D20F0F;margin-top: .85rem">'+shopPrice+'</p></div><div><p style="font-size:1.2rem;color: black;margin-top: 1rem;margin-top: 1rem" class="close"> &#xd7;</p></div></div><div class="shopCarMiddle model"><p style="font-size: .7rem;margin-top: .5rem">型号</p><div class="shop_color"></div></div><div class="shopCarMiddle color"><p style="font-size: .7rem;margin-top: .5rem">颜色</p><div class="shop_color"></div></div><div class="shopCarFooter"><p>数量</p><div><div class="reduce">-</div><div class="count">'+shopNum+'</div><div class="add">+</div></div></div><div class="jionShopCar"><a href="javascript:;" id="addShopCar">确定</a></div></div>');
            $('.detailsImg').attr('src',coverUrlImg)
            $('.shopCar').slideDown(500);
            $('.wrapper').show();
            $('.wrapper').css({
                height:$(document).height()+'px'
            });
            $('html').css({
                'overflow':'hidden'
            })
            $(document.body).css({
                'overflow':'hidden'
            })
            //购物车请求
            $.ajax({
                url:address+'/api/1/findbynumber',
                data:{
                    number:$('.shop_info').attr('number'),
                    commodityId:shopID,
                    userId:userID,
                    token:token,
                    version:version,
                    phoneModel:phoneModel,
                    systemVersion:systemVersion,
                    phoneType:phoneType,
                    type:shopType
                },
                dataType:'json',
                success:function (result) {
                    var models='';
                    var colors='';
                    var num=0;
                    var modelArr=result.value.commodityInfo;
                    //型号
                    for(var x in modelArr){
                        for(var y in modelArr[x]){
                            models+='<p>'+y+'</p>';
                        }
                    }
                    $('.model .shop_color').html(models);
                    $('.model .shop_color p').each(function () {
                        if($(this).text()==modelName){
                            $(this).addClass('shoCar_active')
                        }
                        $(this).on('click',function(){
                            $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                            $('.color .shop_color').html('');
                            //对应型号的颜色
                            if($(this).hasClass('shoCar_active')){
                                var color=$(this).text();
                                colors='';
                                for(var x in modelArr[0][color][0]){
                                    colors+='<p id="'+modelArr[0][color][0][x]['id']+'">'+x+'</p>'
                                }
                                $('.color .shop_color').html(colors)
                            }
                        });

                    })
                    //颜色
                    for(var z in modelArr[0][modelName][0]) {
                        var id=modelArr[0][modelName][0][z]['id'];
                        colors += '<p id="'+id+'">' + z + '</p>'
                    }
                    $('.color .shop_color').html(colors);
                    $('.color .shop_color p').each(function () {
                        if($(this).text()==colorName){
                            $(this).addClass('shoCar_active')
                        }
                        $(this).on('click',function(){
                            $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                        })

                    })
                    $('.model .shop_color p').each(function () {
                        if($(this).text()==modelName){
                            $(this).addClass('shoCar_active')
                        }
                        $(this).on('click',function(){
                            $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                            $('.color .shop_color').html('');
                            //对应型号的颜色
                            if($(this).hasClass('shoCar_active')){
                                var color=$(this).text();
                                colors='';
                                for(var x in modelArr[0][color][0]){
                                    colors+='<p id="'+modelArr[0][color][0][x]['id']+'">'+x+'</p>'
                                }
                                $('.color .shop_color').html(colors)
                                $('.color .shop_color p').each(function () {
                                    if($(this).text()==colorName){
                                        $(this).addClass('shoCar_active')
                                    }
                                    $(this).on('click',function(){
                                        $(this).addClass('shoCar_active').siblings().removeClass('shoCar_active');
                                    })

                                })
                            }
                        });

                    })
                },error:function () {
                    console.log('加载失败')
                }
            })
            //商品数量
            //减少商品数
            $('.reduce').on('click',function () {
                if(num==1){
                    num=1
                }else {
                    num--;
                }
                $('.count').html(num);

            })
            //增加商品数
            $('.add').on('click',function () {
                num++;
                $('.count').html(num);
            })
            //关闭购物车弹框
            $('.close').click(function () {
                $('.shopCar').slideUp(500);
                $('.wrapper').hide();
                $('html').css({
                    'overflow':'visible'
                })
                $(document.body).css({
                    'overflow':'visible'
                })
                setTimeout(function () {
                    $('.shopCar').remove();
                },500)
            })
            //确定加入购物车
            $('#addShopCar').on('click',function(){
                selectShopId=$('.shop_color:eq(1)').find('.shoCar_active').attr('id')
                $('.shopCar').slideUp(500);
                $('.wrapper').hide();
                $('html').css({
                    'overflow':'visible'
                })
                $(document.body).css({
                    'overflow':'visible'
                });
                var s=parseInt($('.count').text());
                if(s>stock){
                    $(document.body).append('<div class="cancelCollect"><p>库存不足，掌柜的正在备货，请稍等~ </p></div>');
                    $('.cancelCollect').css({
                        left:($(document).innerWidth()-$('.cancelCollect').innerWidth())/2+'px',
                    });
                    setTimeout(function () {
                        $('.cancelCollect').remove()
                    },1000)
                }else{
                    $.ajax({
                        url:address+'/api/1/cart/addshoppingcart',
                        data:{
                            amount:$('.count').text(),
                            commodityId:selectShopId,
                            userId:userID,
                            token:token,
                            version:version,
                            phoneModel:phoneModel,
                            systemVersion:systemVersion,
                            phoneType:phoneType,
                            type:shopType
                        },
                        dataType:'json',
                        success:function (result) {
                            $('.shopCar').slideUp(500);
                            $('.wrapper').hide();
                            if(result.resultCode==200){
                                $(document.body).append('<div class="cancelCollect"><p>添加购物车成功</p></div>');
                                $('.cancelCollect').css({
                                    left:($(document).innerWidth()-$('.cancelCollect').innerWidth())/2+'px'
                                });
                                setTimeout(function () {
                                    $('.cancelCollect').remove()
                                },1000)
                            }
                        },error:function () {
                            console.log('加载失败')
                        }
                    })
                }
                setTimeout(function () {
                    $('.shopCar').remove();
                },500)
                $('.shopNum').text($('.count').text());
                $('.shopModel').text($('.shoCar_active').eq(0).text())
                $('.shopColor').text($('.shoCar_active').eq(1).text());
            })
        }

    })
    //客服
    $('.custom_server').on('click',function(){
        var test1={
            subjectImpl:function(){
                SubjectJavaScriptImpl.goCallToPhone(contactPhone);
            }
        };
        test1.subjectImpl()
        if(!$(this).hasClass('selectCusSer')){
            $(this).attr('class','custom_server selectCusSer');
            $(this).find('img').attr('src','../images/mall_kefu_h.svg');
        }else {
            $(this).removeClass('selectCusSer');
            $(this).find('img').attr('src','../images/mall_kefu.svg');
        }
    })
    //收藏
    //是否收藏
    if(collectionStatus==2){
        $('.collect').find('img').attr('src','../images/mall_collect.svg');
        $('.collect').find('dd').html('收藏')
    }else if(collectionStatus==1){
        $('.collect').find('img').attr('src','../images/mall_collect_h.svg');
        $('.collect').find('dd').html('已收藏')
    }
    $('.collect').on('click',function() {
        if(token=='f47ae89213514fa79dad5107662e9c24'){
            var test2={
                subjectImp1:function(){
                    SubjectJavaScriptImpl.loginOUT('never_have_bug');
                }
            };
            test2.subjectImp1();
        }else{
            //收藏请求
            $.ajax({
                url:address+'/api/1/usersaveorcanncelshopcollection',
                data:{
                    userId:userID,
                    commodityId:shopID,
                    token:token,
                    version:version,
                    phoneModel:phoneModel,
                    systemVersion:systemVersion,
                    phoneType:phoneType
                },
                dataType:'json',
                success:function(result){
                    //alert(result.value);
                    console.log(result);
                    if(result.value==2){
                        $('.collect').find('img').attr('src','../images/mall_collect.svg');
                        $(document.body).append('<div class="cancelCollect"><p>取消收藏成功</p></div>');
                        $('.cancelCollect').css({
                            left:($(document).innerWidth()-$('.cancelCollect').innerWidth())/2+'px'
                        });
                        setTimeout(function () {
                            $('.cancelCollect').remove()
                        },1000)
                        $('.collect').find('dd').html('收藏')
                    }else if(result.value==1){
                        $('.collect').find('img').attr('src','../images/mall_collect_h.svg')
                        $('.collect').find('dd').html('已收藏')
                    }
                },error:function(){
                    console.log('加载失败')
                }
            })
        }
    })
    //tab切换
    $('.shopInfo_tab li').on('click',function(){
        $(this).attr('class','active').siblings().removeClass('active');
        if($(this).index()==0){
            //图文详情tab
            $('.image-text_details').show();
            $('.parameter').hide();
            $('.packing').hide();
        }else if($(this).index()==1){
            //产品参数tab
            $('.image-text_details').hide();
            $('.parameter').show();
            $('.packing').hide();
        }else if($(this).index()==2){
            //包装售后tab
            $('.image-text_details').hide();
            $('.parameter').hide();
            $('.packing').show();
        }

    })
    //回到顶部
    var backButton=$('#toTop');
    function backToTop() {
        $('html,body').animate({
            scrollTop: 0
        }, 800);
    }
    backButton.on('click', backToTop);

    $(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时，回到顶部按钮就显示 */
        if ($(window).scrollTop() > $(window).height())
            backButton.fadeIn();
        else
            backButton.fadeOut();
    });
    $(window).trigger('scroll');/*触发滚动事件，避免刷新的时候显示回到顶部按钮*/
    $(window).on('scroll',function () {
        var oTop = $(".fixedDiv").offset().top;
        var sTop = 0;
        $(window).scroll(function(){
            sTop = $(this).scrollTop();
            if(sTop >= oTop){
                $(".shopInfo_tab").css({"position":"fixed","top":"-10px"});
            }else{
                $(".shopInfo_tab").css({"position":"static"});
            }
        });
    })
})